
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "nvs_flash.h"

#include "lvgl.h"
#include "bsp_board.h"         //1.方案板参数配置初始化必须包含的头文件
#include "lvgl_wifi_connect.h" //2.方案板LVGL_wifi接口初始化必须包含的头文件
#include "mqtt_client.h"
#include "lv_demos.h"
#include <string.h>
#include <sys/param.h>
#include "driver/i2c.h"

#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_http_client.h"
#include "gui_app/ui.h"
static const char *TAG = "app_main";
EventGroupHandle_t tcp_event_group; // wifi建立成功信号量
extern lv_obj_t *ui_Panel1;
extern lv_obj_t *ui_TextArea1;
lv_obj_t *ui_wifi_ground[30];
lv_obj_t *ui_wifi_ssid[30];
lv_obj_t *ui_wifi_rssi[30];
esp_lcd_panel_handle_t my_lcd_panel;
void ui_event_WifiTable(lv_event_t *e) // 点击wifi名称回调
{
    lv_event_code_t event_code = lv_event_get_code(e);
    lv_obj_t *target = lv_event_get_target(e);
    if (event_code == LV_EVENT_CLICKED)
    {
        _ui_label_set_property(ui_Label3, _UI_LABEL_PROPERTY_TEXT, lv_label_get_text(ui_wifi_ssid[(int)e->user_data]));
    }
    if (event_code == LV_EVENT_CLICKED)
    {
        _ui_screen_change(&ui_Screen2, LV_SCR_LOAD_ANIM_MOVE_LEFT, 200, 0, &ui_Screen2_screen_init);
    }
}

void wifi_scan() // 扫描可用wifi
{

    wifi_scan_init();
    // 延迟2秒,等待扫描结束
    vTaskDelay(2000 / portTICK_PERIOD_MS);
    // 存储可用 Wi-Fi 热点数量
    uint16_t ap_num;

    // 获取可用 Wi-Fi 热点数量
    esp_wifi_scan_get_ap_num(&ap_num);
    if (ap_num == 0)
    {
        // 如果没有可用 Wi-Fi 热点，输出提示信息
        ESP_LOGI(TAG, "No AP found");
        return;
    }
    // 存储 Wi-Fi 热点信息的指针
    wifi_ap_record_t *ap_records;
    // 分配内存空间存储 Wi-Fi 热点信息
    ap_records = (wifi_ap_record_t *)malloc(sizeof(wifi_ap_record_t) * ap_num);
    if (!ap_records)
    {
        ESP_LOGE(TAG, "malloc error");
        return;
    }
    // 获取所有可用 Wi-Fi 热点信息
    ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&ap_num, ap_records));

    // 输出可用 Wi-Fi 热点数量
    ESP_LOGI(TAG, "Found %d APs", ap_num);

    // 遍历所有可用 Wi-Fi 热点，并输出信息
    for (int i = 0; i < ap_num; i++)
    {
        ui_wifi_ground[i] = lv_obj_create(ui_Panel1);
        lv_obj_set_width(ui_wifi_ground[i], 480);
        lv_obj_set_height(ui_wifi_ground[i], 20);
        lv_obj_set_x(ui_wifi_ground[i], 0);
        lv_obj_set_y(ui_wifi_ground[i], -80 + i * 25);
        lv_obj_set_align(ui_wifi_ground[i], LV_ALIGN_CENTER);
        lv_obj_clear_flag(ui_wifi_ground[i], LV_OBJ_FLAG_SCROLLABLE); /// Flags
        lv_obj_add_event_cb(ui_wifi_ground[i], ui_event_WifiTable, LV_EVENT_ALL, i);

        ui_wifi_ssid[i] = lv_label_create(ui_wifi_ground[i]);
        lv_obj_set_width(ui_wifi_ssid[i], LV_SIZE_CONTENT);
        lv_obj_set_height(ui_wifi_ssid[i], LV_SIZE_CONTENT);
        lv_obj_set_x(ui_wifi_ssid[i], 0);
        lv_obj_set_y(ui_wifi_ssid[i], 0);
        lv_obj_set_align(ui_wifi_ssid[i], LV_ALIGN_CENTER);
        lv_label_set_text(ui_wifi_ssid[i], (const char *)ap_records[i].ssid);

        // ESP_LOGI(TAG, "SSID:%s\t RSSI:%d\t BSSID:" MACSTR, ap_records[i].ssid, ap_records[i].rssi, MAC2STR(ap_records[i].bssid));
    }
    // 释放内存
    free(ap_records);
}

static void log_error_if_nonzero(const char *message, int error_code)
{
    if (error_code != 0)
    {
        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
    }
}

static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id);
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;
    switch ((esp_mqtt_event_id_t)event_id)
    {
    case MQTT_EVENT_CONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
        msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 0);
        ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);

        msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
        ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

        // msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
        // ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

        // msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
        // ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        break;

    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
        ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_DATA:
        ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
        printf("DATA=%.*s\r\n", event->data_len, event->data);
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT)
        {
            log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
            log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
            log_error_if_nonzero("captured as transport's socket errno", event->error_handle->esp_transport_sock_errno);
            ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
        }
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}

void mqtt_app_start(void)
{
    //  等待WIFI网络连接，死等
    xEventGroupWaitBits(tcp_event_group, WIFI_CONNECTED_BIT, false, true, portMAX_DELAY);
    esp_mqtt_client_config_t mqtt_cfg = {

        .broker.address.uri = "mqtt://39.98.34.126:1883"};
#if CONFIG_BROKER_URL_FROM_STDIN
    char line[128];

    if (strcmp(mqtt_cfg.broker.address.uri, "FROM_STDIN") == 0)
    {
        int count = 0;
        printf("Please enter url of mqtt broker\n");
        while (count < 128)
        {
            int c = fgetc(stdin);
            if (c == '\n')
            {
                line[count] = '\0';
                break;
            }
            else if (c > 0 && c < 127)
            {
                line[count] = c;
                ++count;
            }
            vTaskDelay(10 / portTICK_PERIOD_MS);
        }
        mqtt_cfg.broker.address.uri = line;
        printf("Broker url: %s\n", line);
    }
    else
    {
        ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
        abort();
    }
#endif /* CONFIG_BROKER_URL_FROM_STDIN */

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
}

void wifi_set_ok() // 设置wifi
{
    esp_wifi_disconnect();
    char *a = lv_label_get_text(ui_Label3);
    char *b = lv_textarea_get_text(ui_TextArea1);
    uint8_t c[strlen(a)];
    uint8_t d[strlen(b)];
    for (uint8_t i = 0; *(a + i) != '\0'; i++)
    {
        c[i] = *(a + i);
    }
    for (uint8_t i = 0; *(b + i) != '\0'; i++)
    {
        d[i] = *(b + i);
    }

    wifi_config_t wifi_config = {
        .sta = {
            .threshold.authmode = WIFI_AUTH_WPA2_PSK,
            .sae_pwe_h2e = WPA3_SAE_PWE_BOTH,
        },
    };

    memcpy(wifi_config.sta.ssid, c, sizeof c);
    memcpy(wifi_config.sta.password, d, sizeof d);

    // 配置
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_connect()); // 连接网络
    mqtt_app_start();
    //   _ui_screen_change( &ui_Screen1, LV_SCR_LOAD_ANIM_MOVE_LEFT, 200, 0, &ui_Screen1_screen_init);
}

void app_main(void)
{
    tcp_event_group = xEventGroupCreate(); // 创建wifi事件组
    ESP_ERROR_CHECK(nvs_flash_init());     // nvs存储初始化

    // 1.方案板参数配置初始化
    sys_int();
    // 2.方案板LVGL接口初始化
    lvgl_init_wifi();
    // 3.LVGL应用层,用户程序
    lv_port_sem_take1();
    ui_init();

    //    lv_demo_music();//LVGL官方例程1
    // lv_demo_widgets();//LVGL官方例程2
    // lv_demo_benchmark();//LVGL官方例程3
    // lv_demo_stress();//LVGL官方例程4
    lv_port_sem_give1();
}
